<template>
  <div class="sign-in">
    <van-row class="mapbox">
      <baidu-map class="bm-view" :zoom="zoom" :center="center" @ready="handler" ak="BDv3WGThhC19xh6bVCjALzUscGSWxzaS">
      </baidu-map>
      <div class="siginBox">
        <div class="PositioningBack">
          <div @click="clickGcFn" :class="isSignFlag ? '' : 'isSignFlag'">
            <p style="font-size: 0.4130px; margin-top: 0.7rem">{{ nowTime }}</p>
            <p style="font-size: 20px">签到</p>
          </div>
        </div>
      </div>
      <div class="Positioningtips">
        <p class="isshow_Singn" v-if="isSignFlag"><i></i>已进入签到范围</p>
        <p class="notshow_Singn" v-else style="color: #e85656"><i></i>不在签到范围内</p>
      </div>
    </van-row>
    <van-dialog
      v-model="isshow_Singn_diglog"
      confirmButtonText="我知道了"
      confirmButtonColor="#5F6FAB"
      @confirm="confirm"
    >
      <!-- <van-col class="positioncls_img" span="24" offset="10"
          ><img src="../../assets/img/icon_checkinsucceeded.png" alt=""
        /></van-col> -->
      <p style="font-size: 16px; color: black; font-weight: 600; text-align: center; margin-top: 22px">签到成功</p>
      <p
        style="
          font-size: 16px;
          color: black;
          font-weight: 600;
          text-align: center;
          margin-top: 20px;
          margin-bottom: 10px;
        "
      >
        {{ sigNinTime }}
      </p>
    </van-dialog>
  </div>
</template>


<style scope lang="scss">
.sign-in {
  height: 100vh;
  width: 100vw;
  .sinbox {
    font-size: 14px;
    color: #333333;
    font-weight: 800;
    text-align: center;
    width: 100%;
    margin-top: 12px;
  }
  .sinbox p {
    margin: 6px 0rem;
  }
  .sinbox span {
    color: #5f6fab;
  }
  .sinbox p:last-child {
    color: #e5b03c;
    font-weight: 400;
  }
  // map 地图样式
  .bm-view {
    width: 100%;
    height: 55vh;
  }
  .mapbox {
    width: 100%;
    height: 100vh;
  }
  .siginBox {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 18px;
  }
  .PositioningBack p {
    color: #ffffff;
    font-weight: bold;
    text-align: center;
    line-height: 114px;
  }
  .PositioningBack {
    width: 160px;
    height: 160px;
    border: 1px solid #5683e8;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .PositioningBack div {
    width: 140px;
    height: 140px;
    background: linear-gradient(0deg, #5683e8, #56b6e8);
    box-shadow: 0px 11px 21px 0px rgba(86, 133, 232, 0.39);
    border-radius: 50%;
  }
  .Positioningtips i {
    // background: url('../../assets/img/checkinscope_yes.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
    // width: 14px;
    // height: 14px;
    // display: block;
    // float: left;
    // margin-left: 2.130px;
    // margin-right: 6px;
    // margin-top: 6px;
  }
  .Positioningtips {
    margin-top: 12px;
    position: relative;
  }
  .Positioningtips p {
    // width: 100vw;
    font-size: 18px;
    color: black;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
  }

  .notshow_Singn i {
    // background: url('../../assets/img/checkinscope_no.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
  }
  .isSignFlag {
    background: #9f9f9f !important;
  }
  .positioncls_img {
    width: 82px;
    height: 86px;
    margin-top: 18px;
    margin-bottom: 12px;
  }
  .positioncls_img img {
    width: 100%;
    height: 100%;
  }
  .position_text {
    color: #333333;
    font-size: 14px;
    font-weight: bold;
  }
  .position_text p {
    margin: 6px 0 0.9rem 14px;
    font-size: 14px;
    font-weight: 400;
  }
}
</style>


<script>
import BaiduMap from 'vue-baidu-map/components/map/Map.vue'
import { QuerySignCallback } from '@/utils/api'
import { Loading, MessageBox } from 'element-ui'
import { v4 as uuidv4 } from 'uuid';
import timeFormat from "@/utils/timeFormat.js";
export default {
  data() {
    return {
      sinnumber: '432',
      center: { lng: 0, lat: 0 },
      zoom: 3, //必须写上,自己因为忘记写一直无法自动定位
      datetime: null,
      nowTime: '',
      gc: {}, //地理解析
      pt: '', // 我的签到位置
      isSignFlag: true,
      longitude: '120.146469,30.293831', //经纬度
      Range: 500, //签到范围
      isshow_Singn_diglog: false,
      sigNinTime: '',
      points: {},
      cityname:"",
      userData:{}
    }
  },
  components: {
    BaiduMap,
  },
  created() {
    //传入当前村镇的经纬度作为定位依据
    this.cityname = this.$route.query.longitude
    this.userData = JSON.parse(this.$route.query.data)
    console.log(this.userData,'xioahe')
    this.geolocationt1(this.cityname)
    // this.longitude = this.$route.query.longitude
    this.Range = this.$route.query.Range
    console.log(this.$route.query.longitude, this.$route.query.Range, '小何')
    window.onresize = () => {
      return (() => {
        // this.setRem(document)
      })()
    }
    this.$nextTick(() => {
      // this.setRem(document)
      // this.createQrcode()
    })
  },
  mounted() {
    this.datetime = setInterval(() => {
      this.setNowTimes()
    }, 1000)
  },
  methods: {
    handler({ BMap, map }) {
      //loading kaishi
      let loadingInstance = Loading.service({
        lock: true,
        customClass: 'z-index999',
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.2)',
      })
      let that = this
      var point = new BMap.Point(116.331398, 39.897445) //创建定坐标
      map.centerAndZoom(point, 15) //// 初始化地图,设置中心点坐标和地图级别
      var geolocation = new BMap.Geolocation()
      this.gc = new BMap.Geocoder() //创建地理编码器、
      var pointAttendance
      // 开启SDK辅助定位
      geolocation.enableSDKLocation()
      geolocation.getCurrentPosition(
        function (r) {
          console.log(r, 'dddd')
          if (!r.longitude) {
            that.$dialog.alert({ message: '请您打开浏览器定位权限' }).then((resd) => {
              that.$router.push('/signIn')
            })
          }
          if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            var mk = new BMap.Marker(r.point)
            map.addOverlay(mk)
            map.panTo(r.point)
            // alert('您的位置：' + r.point.lng + ',' + r.point.lat);
            let parm = r.point.lng + ',' + r.point.lat
            that.geolocationt1(parm)
            console.log(r.point, that.points)
            point = new BMap.Point(r.point.lng, r.point.lat) // 获取自己的签到位置
            that.pt = r.point
            map.panTo(that.pt) //移动地图中心点
            var coordinate = that.longitude // 设置考勤点经纬度  "116.321854,39.893237"
            console.log(coordinate, 'ledfjioe4')
            var arr = coordinate.split(',') // 切割经纬度
            var lon = arr[0]
            var lat = arr[1]
            pointAttendance = new BMap.Point(lon, lat)
            var circle = new BMap.Circle(pointAttendance, that.Range, {
              // 考勤地点范围
              fillColor: 'blue', // 圆形颜色
              strokeWeight: 1,
              fillOpacity: 0.2,
              strokeOpacity: 0.2,
            })
            map.addOverlay(circle)
            // 考勤的经纬度获取
            var r = new BMap.Marker(pointAttendance)
            map.addOverlay(r) // 标出考勤点的位置
            // 逆向编码
            var myGeo = new BMap.Geocoder()
            myGeo.getLocation(new BMap.Point(r.point.lng, r.point.lat), function (result) {
              if (result) {
                // that.address = result.address
                // alert(result.address)
              }
            })
            // 计算签到与当前位置之间的差值
            var distance = map.getDistance(point, pointAttendance).toFixed(2)
            console.log(distance,'hzl')
            if (Number(distance) > Number(that.Range)) {
              debugger
              that.isSignFlag = false
            }
            loadingInstance.close()
          } else {
            alert('failed' + this.getStatus())
          }
        },
        { enableHighAccuracy: true }
      )
    },
    // getpoint ({ BMap, map }) {
    // 	const val = this.$route.query.longitude
    //   const map = new BMap.Map('map');
    //   map.enableScrollWheelZoom(); // 启用滚轮放大缩小，默认禁用
    //   map.enableContinuousZoom(); // 启用地图惯性拖拽，默认禁用

    // 	localSearch.search(val);
    // },
    // 时间定时器
    setNowTimes() {
      //  根据插件获取时分秒
      // this.nowTime = this.$moment().format('HH:mm:ss')
    },
    clickGcFn() {
      let me = this
      if (this.isSignFlag) {
        this.gc.getLocation(this.pt, function (rs) {
          var addComp = rs.addressComponents
          var coords = rs.point.lng + ',' + rs.point.lat
          // https://api.map.baidu.com/geoconv/v1/?coords=114.21892734521,29.575429778924&from=1&to=5&ak=你的密钥
          me.geolocationt1(coords)
          console.log(rs)
          // alert(addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber);
          me.sigNinTime = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber
          me.updataSignIn(coords)
        })
      } else {
        this.$dialog.alert({ message: '您当前位置不在签到范围' })
      }
    },
    //更新签到状态
   async updataSignIn(){

    },
    //更改百度地图最后的定位
    geolocationt1(data) {
      this.$jsonp('http://api.map.baidu.com/geocoding/v3/', {
        address: data, //地址
        output: 'json',
        ak: 'BDv3WGThhC19xh6bVCjALzUscGSWxzaS',
      })
        .then((json) => {
          // 得到我们想要的内容
        //   this.longitude = json.result.location.lng + ',' + json.result.location.lat
          console.log(json,'xiaohe')
        })
        .catch((err) => {
          console.log(err)
        })
    },
    confirm() {},
    async updataSignIn(data) {
      let uuid1 = uuidv4()
      let date = timeFormat(null, "yyyy-mm-dd hh:MM:ss");
      let params = {
        accessCode: '0fb3f6123d1b4fe6851c99532c463f6f',
        cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
        params: {
          dataGuid: 'd795fc12-20b4-494c-a6b6-e3c9c1563059',
          strParams: JSON.stringify([
            {
              ROW_GUID: uuid1,
              TO_ROW_GUID: this.userData.ROW_GUID,
              XY: data,
              SIGNINPERSON: JSON.parse(window.localStorage.getItem('userName')).userName,
              SIGNINPERSONID: JSON.parse(window.localStorage.getItem('userName')).userId,
              SIGNINTIME: date,
              SIGNINPLACE: this.cityname,
            },
          ]),
        },
      }
      const res = await QuerySignCallback(params)
      if(JSON.parse(res.data.data).Success){
        this.isshow_Singn_diglog = true
      } else{
        this.$toast.fail('签到失败！')
      }
    },
  },
  // 销毁页面之后清空定时器
  beforeDestroy() {
    if (this.datetime) {
      clearInterval(this.datetime)
    }
  },
}
</script>
